import axios from "axios";
import Vue from "vue";
// import { Message } from "element-ui";
// import Message from "../components/Message";
import qs from "qs";
// create an axios instance
const service = axios.create({
  // baseURL:
  //   process.env.NODE_ENV == "production" ? "http://gyapi.letuilm.com/" : " ", // url = base url + request url

  baseURL: "https://tlj-api.letuilm.com/", //线上  123
  // baseURL: "http://192.168.1.141:8088/", //后端电脑 111
  changeOrigin: true, //允许跨域
  // crossDomain: true,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
});

const err = error => {
  // console.log("err", error.response);
  if (error.response) {
    const data = error.response.data;
    console.log("错误信息", data);
    // const token = Vue.ls.get(ACCESS_TOKEN)
  }
  return Promise.reject(error);
};
// request interceptor
service.interceptors.request.use(config => {
  // console.log("config", config);
  const token = Vue.ls.get("token"); //本地获取token
  // config.headers["Accept"] =
  // "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3"; // 重置请求头 返回格式
  if (
    config.url.substring(2, 3) === "d" &&
    config.url.substring(3, 4) === "m"
  ) {
    // console.log("config", config);
    config.headers["token"] = token; // 让每个请求携带自定义 token 请根据实际情况自行修改
    //   config.headers["Content-Type"] = "application/json;charset=utf-8";
  }
  return config;
}, err);

// response interceptor
service.interceptors.response.use(response => {
  const res = response.data;
  // console.log('res', JSON.parse(res))
  // console.log('响应器code', res.code)
  return res;
}, err);
// 请求分为get/post
// axios对于get和post的参数的处理方式是不同的
function http(config) {
  if (config.method.toLowerCase() === "post" && !config.headers) {
    // 针对对象 是无法直接处理的 ; qs是一个js库,可以方便的对对象进行序列化处理
    // myAjax  {name:'zx',age:20} ==> name=zs&age=20
    config.data = qs.stringify(config.data, {
      arrayFormat: "repeat",
      allowDots: true
    });
  } else {
    config.params = config.data;
  }
  return service(config);
}

export default http;
export { service as axios };
